var requestTimeout = 1000*5*60; //5 min
var audioElement = new Audio();

function init()
{
    localStorage.sound_played="not_played";    
    if (localStorage.sound_name===undefined && localStorage.sound==="soundOn") {
        localStorage.sound_name = "play_3";
    }    
    loadContent();
}

function btnClicked()
{
    //    showLoader(true);
    //    loadContent();
    showNewIcon(false);
    if (localStorage.news===undefined) {
        loadContent();
    }
    showContent();
    showLoader(false);
    localStorage.sound_played="not_played";
}

function refresh ()
{
    //    showLoader(true);
    loadContent();
    showNewIcon(false);
    showContent();
    showLoader(false);
    localStorage.sound_played="not_played";    
}

function loadContent()
{
    var uqlURL = "http://query.yahooapis.com/v1/public/yql?q=SELECT%20title,link,description,creator,pubDate%20FROM%20feed%20WHERE%20url='http://xorosho.com/rss.xml'&format=json";
    $.get(uqlURL,function(msg){
        var items = msg.query.results.item;
        if (
            localStorage.news===undefined ||
            items[0].pubDate!==localStorage.lastPub
            ) {
            var htmlString = "";
            for(var i=0;i<items.length;i++) {
                htmlString += '<div id="punkt"><a href="'+items[i].link+'" target="_blank">'+items[i].title+'</a><br><p>'
                +items[i].description+'</p><br></div><div id="creator"><strong>Autor: </strong><span>'+items[i].creator+'</span><hr></div>';
            }
            showNewIcon(true);
            playSound();
            localStorage.news = htmlString;
            localStorage.lastPub = items[0].pubDate;
        }
    },'json');
    sheduleRequest();
}

function showContent()
{
    $('#content').html(localStorage.news).find('object','img[src^="http://www.xorosho.com/engine/"]').remove().end().find('img[src^="http://www.xorosho.com/engine/"]').remove();
}

function sheduleRequest()
{
    window.setTimeout(loadContent, requestTimeout);
}

function showNewIcon(display)
{
    display ? chrome.browserAction.setIcon({
        path: "i/icon_19_new.png"
    }) : chrome.browserAction.setIcon({
        path: "i/icon_19.png"
    });
}

function playSound()
{
    if (localStorage.sound==="soundOn" && localStorage.sound_played==="not_played") {
        localStorage.sound_played="played";
        try {
            audioElement.src = localStorage.sound_name+".mp3";
            audioElement.load();
            audioElement.play();
        } catch (e) {
        }    
    }
}

function closePopup()
{
    window.close();
}

function showLoader(display)
{
    display ? $('div#loader').show() : $('div#loader').hide();
}

function showOptions()
{
    chrome.tabs.create({
        url:'options.html'
    });
}